package com.mlink.ai.chat.utils

import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.os.ParcelFileDescriptor
import android.text.TextUtils
import androidx.documentfile.provider.DocumentFile
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException


object FileUtils {


    private fun isExternalStorageMounted(): Boolean {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
    }

    fun getCacheDir(context: Context): File {
        return if (isExternalStorageMounted()) {
            context.externalCacheDir ?: context.cacheDir
        } else {
            context.cacheDir
        }
    }

    fun getFileFromUri(context: Context, uri: Uri): File? {
        var file: File? = null
        val scheme = uri.scheme
        if ((ContentResolver.SCHEME_CONTENT == scheme) || (ContentResolver.SCHEME_FILE == scheme)) {
            val cursor = context.contentResolver.query(uri, null, null, null, null)
            if (cursor != null && cursor.moveToFirst()) {
                val filePath = cursor.getString(cursor.getColumnIndexOrThrow("_data"))
                if (!TextUtils.isEmpty(filePath)) {
                    file = File(filePath)
                }
                cursor.close()
            } else {
                var pfd: ParcelFileDescriptor? = null
                try {
                    pfd = context.contentResolver.openFileDescriptor(uri, "r")
                    if (pfd != null) {
                        val fd = pfd.fileDescriptor
                        file = File(fd.toString())
                    }
                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                } finally {
                    try {
                        pfd?.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        }
        return file
    }

    fun getFileName(context: Context, uri: Uri): String {
        val documentFile = DocumentFile.fromSingleUri(context, uri)
        if (documentFile?.name != null) {
            return documentFile.name!!
        }
        val file = getFileFromUri(context, uri)
        if (file?.name != null) {
            return file.name
        }
        return if (MediaUtils.getMimeType(uri, context).startsWith("video")) {
            "${System.currentTimeMillis()}.jpeg"
        } else {
            "${System.currentTimeMillis()}.mp4"
        }
    }
}